package com.maomao.es.vector;

import org.springframework.stereotype.Service;

import java.util.Arrays;
import java.util.HashMap;
import java.util.Map;

/**
 * @author mao
 * @date 2025-05-30- 14:51
 * @descript
 */
@Service
public class VectorizationService {

    // 使用简单的TF-IDF作为示例，实际可使用BERT等模型
    public float[] textToVector(String text) {
        // 这里简化实现，实际应该使用预训练模型
        String[] words = text.toLowerCase().split("\\s+");
        Map<String, Integer> wordFreq = new HashMap<>();

        for (String word : words) {
            wordFreq.put(word, wordFreq.getOrDefault(word, 0) + 1);
        }

        // 转换为固定维度向量（示例用）
        float[] vector = new float[512];
        Arrays.fill(vector, 0f);

        int i = 0;
        for (Map.Entry<String, Integer> entry : wordFreq.entrySet()) {
            if (i >= 512) break;
            vector[i] = entry.getValue();
            i++;
        }

        return normalizeVector(vector);
    }

    private float[] normalizeVector(float[] vector) {
        double sum = 0;
        for (float v : vector) {
            sum += v * v;
        }
        double norm = Math.sqrt(sum);

        float[] normalized = new float[vector.length];
        for (int i = 0; i < vector.length; i++) {
            normalized[i] = (float) (vector[i] / norm);
        }

        return normalized;
    }

    // 余弦相似度计算
    public float cosineSimilarity(float[] vec1, float[] vec2) {
        if (vec1.length != vec2.length) {
            throw new IllegalArgumentException("Vectors must have same length");
        }

        float dotProduct = 0;
        float norm1 = 0;
        float norm2 = 0;

        for (int i = 0; i < vec1.length; i++) {
            dotProduct += vec1[i] * vec2[i];
            norm1 += vec1[i] * vec1[i];
            norm2 += vec2[i] * vec2[i];
        }

        return (float) (dotProduct / (Math.sqrt(norm1) * Math.sqrt(norm2)));
    }
}
